class Category < ActiveRecord::Base
  has_many :posts, :dependent => :destroy
  acts_as_tree :order => 'name'
  named_scope :find_ancestors, :conditions => {:parent_id => 0}
  delegate :name, :to => :parent, :prefix => true

  # => 父栏目名
  def parent_name
    parent.try(:name) || '顶级栏目'
  end

  # => 找不到父栏目就返回自己
  def parent_or_self
    parent || self
  end

  # => 构造目录选择下拉列表
  def self.select_options
    space_num = 1 # 子目录前空格数，体现层次感。
    options = [['请选择栏目',0]]
    ancestors = find_ancestors
    ancestors.each do |ancestor|
      options << [ancestor.name,ancestor.id]
      ancestor.children.each do |child|
        options << ["#{'　' * space_num}#{child.name}",child.id]
        child.collection_child_options(options,space_num) unless child.children.empty?
      end
    end
    return options
  end

  private
  # => 循环收集子目
  def collection_child_options(options,space_num)
    space_num += 1
    self.children.each do |child|
      options << ["#{'　' * space_num}#{child.name}",child.id]
      child.collection_child_options(options,space_num) unless child.children.empty?
    end
  end

end
